﻿using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Data;
using System.Data.Entity;
using System.IO;
using System.Linq;
using System.Text;
using System.Transactions;
using System.Web;
using System.Web.ModelBinding;
using System.Web.Mvc;
using ZBJF.Warranty.BLL;
using ZBJF.Warranty.Common.Common;
using ZBJF.Warranty.Common.Enums.Certificate;
using ZBJF.Warranty.Common.Enums.InsuranceOrder;
using ZBJF.Warranty.Common.Enums.InsuranceWarranty;
using ZBJF.Warranty.Common.Enums.System;
using ZBJF.Warranty.Model;
using ZBJF.Warranty.Model.ViewModel.InsuranceWarranty;
using ZBJF.Warranty.Model.ViewModel.Order;
using ZBJF.Warranty.WebProvider;

namespace ZBJF.Warranty.CustomerService.Controllers
{
    public class InsuranceWarrantyRecordController : BaseController
    {
        #region 新建报案

        #region 新建报案页面 + ActionResult ToBeCreated()
        public ActionResult ToBeCreated()
        {
            return View();
        }
        #endregion

        #region 获取可报案 保单 + JsonResult GetApprovedInsuranceOrder(InsuranceOrderModel model)
        /// <summary>
        /// 获取可报案 保单
        /// </summary>
        /// <param name="model"></param>
        /// <returns></returns>
        [HttpPost]
        public JsonResult GetApprovedInsuranceOrder(InsuranceOrderModel model)
        {
            //此处应该直接过滤，而不是取审核通过的之后在过滤
            //一定要生效，当前时间一定在 保单有效期内， ServiceStartTime，ServiceEndTime，保单没有有效报案（没有修过）
            var total = 0;
            var list =
                ServiceFactory.InsuranceOrderServiceInstance.GetPagingList(model, out total)
                    .Include(o => o.InsuranceWarrantyRecord)
                    .AsNoTracking()
                    .ToList()
                    .Select(o => new
                    {
                        //o.CardNo,
                        //o.CardPwd,
                        //o.VerificationCertificate,
                        //o.OrderNO,
                        //o.InsuranceCategory,
                        //o.BuyType,
                        //BuyTypeDesc = EnumHelper.Instance.GetDescription(typeof(InsuranceBuyType), o.BuyType),
                        //o.Price,
                        //o.WaitDays,
                        //o.PolicyPeriod,
                        //o.PolicyPeriodUnit,
                        //o.CertificateType,
                        //CertificateTypeDesc =
                        //    EnumHelper.Instance.GetDescription(typeof(UserCertificateType), o.CertificateType),
                        //o.ProductTypeId,
                        //o.ProductTypeName,
                        //o.ProductBrandId,
                        //o.ProductBrandName,
                        //o.ProductModelId,
                        //o.ProductModelName,
                        //o.SaleVendorId,
                        //o.SalePersonName,
                        //o.SaleManagerName,
                        //o.SaleManagerPhone,
                        //o.SaleAddress,
                        //o.OrderStatus,
                        //o.Effective,
                        //o.InsuredAmount,
                        //EffectiveDate = o.EffectiveDate.HasValue ? o.EffectiveDate.Value.ToString("yyyy-MM-dd HH:mm:ss") : "",
                        //OrderStatusDesc =
                        //    EnumHelper.Instance.GetDescription(typeof(InsuranceOrderStatus), o.OrderStatus),
                        //o.LastCheckUser,
                        //LastCheckTime =
                        //    o.LastCheckTime.HasValue ? o.LastCheckTime.Value.ToString("yyyy-MM-dd HH:mm:ss") : "",
                        //o.OrderFromType,
                        //OrderFromTypeDesc =
                        //    EnumHelper.Instance.GetDescription(typeof(InsuranceOrderFromType), o.OrderFromType),
                        //o.CreateBy,
                        //o.LastModifyBy,
                        //LastModifyTime = o.LastModifyTime.ToString("yyyy-MM-dd HH:mm:ss"),
                        o.ID,
                        o.InsuranceCategoryName,
                        o.ProductName,
                        o.UserName,
                        o.UserPhone,
                        o.CertificateNO,
                        o.IMEI,
                        o.SaleVendorName,
                        ServiceStartTime = o.ServiceStartTime.HasValue ? o.ServiceStartTime.Value.ToString("yyyy-MM-dd") : "",
                        ServiceEndTime = o.ServiceEndTime.HasValue ? o.ServiceEndTime.Value.ToString("yyyy-MM-dd") : "",
                        CreateOrderTime = o.CreateOrderTime.ToString("yyyy-MM-dd HH:mm:ss"),
                        o.ThirdOrderNO,
                        o.InsuranceCompany,
                        o.InsuranceCompanyBranch
                    });
            return Json(new
            {
                sEcho = model.sEcho,
                iTotalRecords = total,
                iTotalDisplayRecords = total,
                aaData = list
            }, JsonRequestBehavior.AllowGet);
        }
        #endregion

        #region 新建报案页面--从新建报案列表的操作列进入 + ActionResult Create(int insuranceOrderId)
        public ActionResult Create(int insuranceOrderId)
        {
            // 有取消报案 的单 可以再次创建报案  验证 
            var insuranceWarrantyRecord = ServiceFactory.InsuranceWarrantyRecordServiceInstance
                                            .LoadByInsuranceOrderId(insuranceOrderId)
                                            .FirstOrDefault(c => c.Status != (byte)InsuranceWarrantyStatus.Canceled && c.Status != (byte)InsuranceWarrantyStatus.Refuse) ?? new InsuranceWarrantyRecord();
            if (insuranceWarrantyRecord.InsuranceOrder == null)
                insuranceWarrantyRecord.InsuranceOrder = ServiceFactory.InsuranceOrderServiceInstance.LoadByID(insuranceOrderId);

            var insuranceOrder = insuranceWarrantyRecord.InsuranceOrder;
            var currentTime = DateTime.Now;
            var canCreatedWarranty = insuranceOrder.Effective == true &&
                                    insuranceOrder.OrderStatus == (byte)InsuranceOrderStatus.HadEffective &&
                                     insuranceOrder.ServiceStartTime <= currentTime &&
                                     insuranceOrder.ServiceEndTime >= currentTime &&
                                     (!insuranceOrder.InsuranceWarrantyRecord.Any() ||
                                      insuranceOrder.InsuranceWarrantyRecord.All(
                                          x =>
                                              x.Status == (int)InsuranceWarrantyStatus.Canceled ||
                                              x.Status == (int)InsuranceWarrantyStatus.Refuse));
            ViewBag.CanCreatedWarranty = canCreatedWarranty;

            if (string.IsNullOrEmpty(insuranceWarrantyRecord.Reporter))
                insuranceWarrantyRecord.Reporter = insuranceOrder.UserName;

            if (string.IsNullOrEmpty(insuranceWarrantyRecord.ReporterPhone))
                insuranceWarrantyRecord.ReporterPhone = insuranceOrder.UserPhone;

            return View(insuranceWarrantyRecord);
        }
        #endregion

        #region 新建报案、补充案件信息 + ActionResult SaveInsuranceWarrantyRecord(InsuranceWarrantyRecord model)
        /// <summary>
        /// 新建报案、补充案件信息
        /// </summary>
        /// <param name="model"></param>
        /// <returns></returns>
        [HttpPost]
        [ValidateInput(true)]
        public ActionResult SaveInsuranceWarrantyRecord(InsuranceWarrantyRecord model)
        {
            var responseResult = new ResponseResult
            {
                OpreateType = model.ID > 0 ? OpreateType.Update : OpreateType.Add
            };
            if (ModelState.IsValid)
            {
                using (TransactionScope ts = new TransactionScope())
                {
                    try
                    {
                        var entity = ServiceFactory.InsuranceWarrantyRecordServiceInstance.LoadByID(model.ID);

                        if (entity == null)//新建报案
                        {
                            model.WarrantyRecordNo = CommonMethod.GetTimeStamp();
                            model.CreateTime = DateTime.Now;
                            model.CreateBy = model.LastModifyBy = CurrentUser.UserAccount;
                            model.LastModifyTime = DateTime.Now;
                            model.InsuranceOrder = null;//外键表得置空
                            model.Status = (byte)InsuranceWarrantyStatus.Created;
                            model.SystemServiceUserId = CurrentUser.ID;
                            var resultEntity = ServiceFactory.InsuranceWarrantyRecordServiceInstance.AddEntities(model);
                            responseResult.Success = resultEntity.ID > 0;
                            #region 后记录操作日志
                            var opreateLogs = new OpreateLogs
                            {
                                CreatedTime = DateTime.Now,
                                LogTableName = "InsuranceWarrantyRecord",
                                LogSubject = "新建报案",
                                LogTablePKID = resultEntity.ID,
                                OpreateUserAccount = CurrentUser.UserAccount,
                                OpreateUserName = CurrentUser.UserDisPlayName
                            };
                            var addLogResult = ServiceFactory.OpreateLogsServiceInstance.AddOpreateLogs(opreateLogs, string.Empty, resultEntity, OpreateType.Add);
                            #endregion


                            #region 后记录流程日志
                            InsuranceWarrantyRecordStatus oldStatusInfo = new InsuranceWarrantyRecordStatus { ID = 0, StatusCode = 0, StatusName = "" };
                            InsuranceWarrantyRecordStatus newStatusInfo = ServiceFactory.InsuranceWarrantyRecordStatusServiceInstance.LoadByStatus((byte)InsuranceWarrantyStatus.Created);
                            WriteProcessLog(oldStatusInfo, newStatusInfo, null, resultEntity.ID);
                            #endregion
                        }
                        else//补充案件信息
                        {
                            model.LastModifyBy = CurrentUser.UserAccount;
                            model.LastModifyTime = DateTime.Now;
                            #region 先记录日志
                            var opreateLogs = new OpreateLogs
                            {
                                CreatedTime = DateTime.Now,
                                LogTableName = "InsuranceWarrantyRecord",
                                LogSubject = "补充案件信息",
                                LogTablePKID = entity.ID,
                                OpreateUserAccount = CurrentUser.UserAccount,
                                OpreateUserName = CurrentUser.UserDisPlayName
                            };
                            var logEntity = new
                            {
                                entity.Reporter,
                                entity.ReporterPhone,
                                entity.ContactName,
                                entity.ContactPhone,
                                entity.CreateTime,
                                entity.ExpectAccidentDate,
                                entity.CityId,
                                entity.ProvinceId,
                                entity.AccidentAddress,
                                entity.AccidentProsess,
                                entity.Remark,
                                entity.LastModifyBy,
                                entity.LastModifyTime
                            };
                            var addLogResult = ServiceFactory.OpreateLogsServiceInstance.AddOpreateLogs(opreateLogs, logEntity, model);
                            #endregion
                            entity.Reporter = model.Reporter;
                            entity.ReporterPhone = model.ReporterPhone;
                            entity.ContactName = model.ContactName;
                            entity.ContactPhone = model.ContactPhone;
                            entity.CreateTime = model.CreateTime;
                            entity.ExpectAccidentDate = model.ExpectAccidentDate;
                            entity.CityId = model.CityId;
                            entity.ProvinceId = model.ProvinceId;
                            entity.AccidentAddress = model.AccidentAddress;
                            entity.AccidentProsess = model.AccidentProsess;
                            entity.Remark = model.Remark;
                            entity.LastModifyBy = model.LastModifyBy;
                            entity.LastModifyTime = model.LastModifyTime;
                            responseResult.Success = ServiceFactory.InsuranceWarrantyRecordServiceInstance.UpdateEntities(entity);
                        }
                        ts.Complete();
                    }
                    catch (Exception ex)
                    {
                        responseResult.Message = ex.Message;
                        ts.Dispose();
                    }
                }

            }
            else
            {
                responseResult.Message = "数据校验失败！";
            }
            TempData["ResponseResult"] = responseResult;//新增案件信息（跳转到处理页面）或者是补充案件信息（跳转到补充案件信息页面）
            return responseResult.OpreateType == OpreateType.Add && responseResult.Success ? RedirectToAction("Processing", new { id = model.ID }) : RedirectToAction("Edit", new { id = model.ID });
        }
        #endregion
        #endregion

        #region 报案工单任务页面+处理任务

        #region 报案工单任务列表页面 + ActionResult InsuranceWarrantyRecord()
        public ActionResult InsuranceWarrantyRecord()
        {
            return View();
        }
        #endregion

        #region 获取报案工单任务列表数据 + JsonResult InsuranceWarrantyRecord(InsuranceWarrantyRecordModel model)
        /// <summary>
        /// 获取报案工单任务列表数据
        /// </summary>
        /// <param name="model"></param>
        /// <returns></returns>
        [HttpPost]
        public JsonResult InsuranceWarrantyRecord(InsuranceWarrantyRecordModel model)
        {
            var total = 0;
            var list = ServiceFactory.InsuranceWarrantyRecordServiceInstance.GetPagingList(model, out total).Include(o => o.SystemUser).Include(o => o.InsuranceOrder).AsNoTracking().ToList().Select(o => new
            {
                o.ID,
                o.InsuranceOrderId,
                o.WarrantyRecordNo,
                o.Reporter,
                o.ReporterPhone,
                SendBackTime = o.SendBackTime.HasValue ? o.SendBackTime.Value.ToString("yyyy-MM-dd HH:mm") : "",
                o.Status,
                StatusDesc = ServiceFactory.InsuranceWarrantyRecordStatusServiceInstance.GetStatusName(o.Status),
                CreateTime = o.CreateTime.ToString("yyyy-MM-dd HH:mm"),
                LastModifyTime = o.LastModifyTime.ToString("yyyy-MM-dd HH:mm"),
                ServiceName = o.SystemUser != null ? o.SystemUser.UserDisPlayName : string.Empty,
                SendExpressPickUpTime = o.SendExpressPickUpTime.HasValue ? o.SendExpressPickUpTime.Value.ToString("yyyy-MM-dd HH:mm") : "",
                o.InsuranceOrder.InsuranceCompany,
                o.InsuranceOrder.InsuranceCompanyBranch,
                o.InsuranceOrder.ProductName,
                o.InsuranceOrder.ProductTypeName,
                o.InsuranceOrder.SaleVendorName,
                o.InsuranceOrder.InsuranceCategoryName,
                CostTotalSecond = CommonMethod.TimeSencondToString(o.CostTotalSecond ?? (int)(DateTime.Now - o.CreateTime).TotalSeconds),
            });
            return Json(new
            {
                sEcho = model.sEcho,
                iTotalRecords = total,
                iTotalDisplayRecords = total,
                aaData = list
            }, JsonRequestBehavior.AllowGet);
        }
        #endregion

        #region 获取保单信息 + ActionResult InsuranceOrderInfo(int insuranceOrderId)
        /// <summary>
        /// 获取保单信息
        /// </summary>
        /// <param name="insuranceOrderId"></param>
        /// <returns></returns>
        public ActionResult InsuranceOrderInfo(int insuranceOrderId)
        {
            var order = ServiceFactory.InsuranceOrderServiceInstance.LoadByID(insuranceOrderId);
            return View(order);
        }
        #endregion

        #region 处理任务详细页面 + ActionResult Processing(int id)
        /// <summary>
        /// 处理任务详细页面
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public ActionResult Processing(int id)
        {
            var insuranceWarrantyRecord = ServiceFactory.InsuranceWarrantyRecordServiceInstance.LoadByID(id) ??
                              new InsuranceWarrantyRecord
                              {
                                  InsuranceWarrantyRecordItem = new List<InsuranceWarrantyRecordItem> { new InsuranceWarrantyRecordItem() },
                                  InsuranceWarrantyRecordFree = new List<InsuranceWarrantyRecordFree> { new InsuranceWarrantyRecordFree() }
                              };
            if (!insuranceWarrantyRecord.InsuranceWarrantyRecordItem.Any())
                insuranceWarrantyRecord.InsuranceWarrantyRecordItem = new List<InsuranceWarrantyRecordItem> { new InsuranceWarrantyRecordItem() };
            if (!insuranceWarrantyRecord.InsuranceWarrantyRecordFree.Any())
                insuranceWarrantyRecord.InsuranceWarrantyRecordFree = new List<InsuranceWarrantyRecordFree> { new InsuranceWarrantyRecordFree() };

            //根据状态获取上级状态
            int parentStatusId = 0;  //父级状态
            int parentStatusCode = 0;
            InsuranceWarrantyRecordStatus parentStatusModel = ServiceFactory.InsuranceWarrantyRecordStatusServiceInstance.LoadEntities(t => t.StatusCode == insuranceWarrantyRecord.Status).FirstOrDefault();
            if (parentStatusModel != null)
            {
                parentStatusId = parentStatusModel.ParentId;
                parentStatusCode = parentStatusModel.ParentCode;
            }
            ViewBag.ParentStatusId = parentStatusId;
            ViewBag.ParentStatusCode = parentStatusCode;
            return View(insuranceWarrantyRecord);
        }
        #endregion

        #region 保存案件处理信息 +  ActionResult SaveInsuranceWarrantyRecordItem(InsuranceWarrantyRecord model, int? StatusReasonId)
        /// <summary>
        /// 保存案件处理信息
        /// </summary>
        /// <param name="model"></param>
        /// <param name="StatusReasonId">状态如果有变化，可能会有状态备注</param>
        /// <returns></returns>
        [HttpPost]
        [ValidateInput(true)]
        public ActionResult SaveInsuranceWarrantyRecordItem(InsuranceWarrantyRecord model, int? StatusReasonId)
        {
            var responseResult = new ResponseResult
            {
                OpreateType = model.ID > 0 ? OpreateType.Update : OpreateType.Add
            };
            //根据iD获取工单信息
            var iwrEntity = ServiceFactory.InsuranceWarrantyRecordServiceInstance.LoadByID(model.ID);
            var validateInsuranceOrderMsg = new StringBuilder();
            var validateIWRMsg = new StringBuilder();
            var opreateLogs = new OpreateLogs();
            iwrEntity.WarrantyMaintenanceTypeID = model.WarrantyMaintenanceTypeID; //维修方式
            //iwrEntity.ServiceProviderId = model.ServiceProviderId; //服务商
            iwrEntity.ServiceProviderBranchId = model.ServiceProviderBranchId; //服务商网点
            using (TransactionScope ts = new TransactionScope())
            {
                try
                {
                    if (iwrEntity != null)
                    {
                        // 先记录日志
                        WriteOperateLog(iwrEntity, model);

                        #region 保存设备信息_品牌/型号
                        if (model.InsuranceOrder != null)
                        {
                            if (model.InsuranceOrder.ProductModelId.HasValue)
                            {
                                var s = ServiceFactory.InsuranceOrderServiceInstance;
                                InsuranceOrder insuranceOrder = s.LoadByID(iwrEntity.InsuranceOrderId);
                                insuranceOrder.ProductModelId = model.InsuranceOrder.ProductModelId.Value;
                                insuranceOrder.ProductModelName = ServiceFactory.ProductModelsServiceInstance.GetModelName(model.InsuranceOrder.ProductModelId.Value);
                                if (model.InsuranceOrder.ProductBrandId.HasValue)
                                {
                                    insuranceOrder.ProductBrandId = model.InsuranceOrder.ProductBrandId.Value;
                                    insuranceOrder.ProductBrandName = ServiceFactory.ProductBrandsServiceInstance.GetBrandName(model.InsuranceOrder.ProductBrandId.Value);
                                }
                                s.UpdateEntities(insuranceOrder);
                            }
                        }
                        #endregion

                        #region 处理信息集合
                        var insuranceWarrantyRecordItemList = model.InsuranceWarrantyRecordItem.ToList();
                        var iwrItemsIds = new List<long>();
                        foreach (var entity in insuranceWarrantyRecordItemList)
                        {
                            entity.InsuranceWarrantyRecordId = model.ID;
                            var entity1 = entity;
                            var insuranceWarrantyRecordItem =
                                ServiceFactory.InsuranceWarrantyRecordItemServiceInstance.LoadEntities(o => o.ID == entity1.ID).AsNoTracking().FirstOrDefault();//不修改的需要加AsNoTracking
                            if (insuranceWarrantyRecordItem != null)
                            {
                                iwrItemsIds.Add(entity.ID);
                                // 先记录日志
                                WriteItemOperateLog(iwrEntity.ID, entity, insuranceWarrantyRecordItem);

                                responseResult.Success = ServiceFactory.InsuranceWarrantyRecordItemServiceInstance.UpdateEntities(entity);
                            }
                            else
                            {
                                if (!string.IsNullOrEmpty(entity.LostName))
                                {
                                    var addedEntity =
                                        ServiceFactory.InsuranceWarrantyRecordItemServiceInstance.AddEntities(entity);

                                    #region 先记录日志
                                    opreateLogs = new OpreateLogs
                                    {
                                        CreatedTime = DateTime.Now,
                                        LogTableName = "InsuranceWarrantyRecord",
                                        LogSubject = "案件处理信息-新增",
                                        LogTablePKID = iwrEntity.ID,
                                        OpreateUserAccount = CurrentUser.UserAccount,
                                        OpreateUserName = CurrentUser.UserDisPlayName
                                    };
                                    ServiceFactory.OpreateLogsServiceInstance.AddOpreateLogs(opreateLogs, string.Empty,
                                        entity, OpreateType.Add);

                                    #endregion

                                    iwrItemsIds.Add(addedEntity.ID);
                                    responseResult.Success = addedEntity.ID > 0;
                                }
                            }
                        }
                        //删除
                        if (iwrItemsIds.Any())
                        {
                            responseResult.Success = ServiceFactory.InsuranceWarrantyRecordItemServiceInstance.DeleteBy(model.ID, iwrItemsIds, CurrentUser.UserAccount, CurrentUser.UserDisPlayName);
                        }
                        #endregion

                        #region 其他费用处理集合
                        var insuranceWarrantyRecordFreeList = model.InsuranceWarrantyRecordFree.ToList();
                        var iwrFreeIds = new List<long>();
                        foreach (var entity in insuranceWarrantyRecordFreeList)
                        {
                            if (entity.FeeType <= 0 && entity.Amount <= 0)
                            {
                                continue;
                            }
                            entity.InsuranceWarrantyRecordId = model.ID;
                            var entity1 = entity;
                            var insuranceWarrantyRecordFree =
                                ServiceFactory.InsuranceWarrantyRecordFreeServiceInstance.LoadEntities(o => o.ID == entity1.ID).AsNoTracking().FirstOrDefault();//不修改的需要加AsNoTracking
                            if (insuranceWarrantyRecordFree != null)
                            {
                                iwrFreeIds.Add(entity.ID);
                                #region 先记录日志
                                opreateLogs = new OpreateLogs
                                {
                                    CreatedTime = DateTime.Now,
                                    LogTableName = "InsuranceWarrantyRecord",
                                    LogSubject = "其他费用处理集合-修改",
                                    LogTablePKID = iwrEntity.ID,
                                    OpreateUserAccount = CurrentUser.UserAccount,
                                    OpreateUserName = CurrentUser.UserDisPlayName
                                };
                                ServiceFactory.OpreateLogsServiceInstance.AddOpreateLogs(opreateLogs, new
                                {
                                    insuranceWarrantyRecordFree.FeeType,
                                    insuranceWarrantyRecordFree.Amount
                                }, entity);
                                #endregion
                                responseResult.Success = ServiceFactory.InsuranceWarrantyRecordFreeServiceInstance.UpdateEntities(entity);
                            }
                            else
                            {
                                var addedEntity = ServiceFactory.InsuranceWarrantyRecordFreeServiceInstance.AddEntities(entity);
                                #region 先记录日志
                                opreateLogs = new OpreateLogs
                                {
                                    CreatedTime = DateTime.Now,
                                    LogTableName = "InsuranceWarrantyRecord",
                                    LogSubject = "其他费用处理集合-新增",
                                    LogTablePKID = iwrEntity.ID,
                                    OpreateUserAccount = CurrentUser.UserAccount,
                                    OpreateUserName = CurrentUser.UserDisPlayName
                                };
                                ServiceFactory.OpreateLogsServiceInstance.AddOpreateLogs(opreateLogs, string.Empty, entity, OpreateType.Add);
                                #endregion
                                iwrFreeIds.Add(addedEntity.ID);
                                responseResult.Success = addedEntity.ID > 0;
                            }
                        }
                        //删除
                        if (iwrFreeIds.Any())
                        {
                            responseResult.Success = ServiceFactory.InsuranceWarrantyRecordFreeServiceInstance.DeleteBy(model.ID, iwrFreeIds, CurrentUser.UserAccount, CurrentUser.UserDisPlayName);
                        }
                        #endregion

                        #region 关单需要信息完整
                        if (iwrEntity.Status != model.Status && model.Status == (byte)InsuranceWarrantyStatus.Close)
                        {
                            InsuranceOrder insuranceOrder =
                                ServiceFactory.InsuranceOrderServiceInstance.LoadByID(iwrEntity.InsuranceOrderId);
                            //验证保单必填数据
                            string validateIWR;
                            validateInsuranceOrderMsg.Append(ValidateInsuranceOrderFormData(insuranceOrder, out validateIWR));
                            validateIWRMsg.Append(validateIWR);
                            validateIWRMsg.Append(string.Empty);
                            //验证报案单数据
                            validateIWRMsg.Append(ValidateInsuranceWarrantyRecordFormData(iwrEntity));

                            if (!iwrEntity.CostTotalSecond.HasValue)//第一次关单，记录总耗时
                                iwrEntity.CostTotalSecond = (int)(DateTime.Now - iwrEntity.CreateTime).TotalSeconds;
                        }
                        #endregion

                        #region 报案工单状态发生改变 + 写操作流程日志
                        if (iwrEntity.Status != model.Status)
                        {
                            //获取父级状态
                            var service = ServiceFactory.InsuranceWarrantyRecordStatusServiceInstance;
                            InsuranceWarrantyRecordStatus newStatusInfo = service.LoadEntities(t => t.StatusCode == model.Status).FirstOrDefault();
                            //已处理需要信息完整
                            if (newStatusInfo.StatusCode == (byte)InsuranceWarrantyStatus.Close && iwrEntity.InsuranceWarrantyRecordItem.Count == 0)
                            {
                                validateIWRMsg.Append("案件处理信息不能为空！<br/>");
                            }

                            //记录流程日志
                            InsuranceWarrantyRecordStatus oldStatusInfo = service.LoadEntities(t => t.StatusCode == iwrEntity.Status).FirstOrDefault();
                            WriteProcessLog(oldStatusInfo, newStatusInfo, StatusReasonId, model.ID);
                        }
                        #endregion

                        //有没有数据错误信息
                        string orderMsg = validateInsuranceOrderMsg.ToString(), IWRMsg = validateIWRMsg.ToString();
                        if (!string.IsNullOrEmpty(orderMsg) || !string.IsNullOrEmpty(IWRMsg))
                        {
                            if (!string.IsNullOrEmpty(orderMsg))
                            {
                                responseResult.Message = "保单信息不完整：" + orderMsg;
                            }
                            if (!string.IsNullOrEmpty(IWRMsg))
                            {
                                responseResult.Message += "案件信息不完整：" + IWRMsg;
                            }
                            TempData["ResponseResult"] = responseResult;
                            return RedirectToAction("Processing", new { id = model.ID });
                        }
                        iwrEntity.RepairRemark = model.RepairRemark;
                        iwrEntity.Status = model.Status;
                        iwrEntity.LastModifyTime = DateTime.Now;
                        iwrEntity.LastModifyBy = CurrentUser.UserAccount;
                        responseResult.Success = ServiceFactory.InsuranceWarrantyRecordServiceInstance.UpdateEntities(iwrEntity);
                        ts.Complete();
                    }
                }
                catch (Exception ex)
                {
                    ts.Dispose();
                    LogHelper.WriteLog("保存报案工单信息错误：" + ex.ToString(), LogType.error);
                }
            }
            TempData["ResponseResult"] = responseResult;
            return RedirectToAction("Processing", new { id = model.ID });
        }

        #region 验证保单数据完整性 + string ValidateInsuranceOrderFormData(InsuranceOrder insuranceOrder, out string validateIWRMsg)
        /// <summary>
        /// 验证保单数据完整性
        /// </summary>
        /// <param name="insuranceOrder"></param>
        /// <returns></returns>
        internal string ValidateInsuranceOrderFormData(InsuranceOrder insuranceOrder, out string validateIWRMsg)
        {
            StringBuilder validateInsuranceOrderMsg = new StringBuilder();
            validateIWRMsg = string.Empty;
            if (string.IsNullOrEmpty(insuranceOrder.InsuranceCompanyBranch))
            {
                validateInsuranceOrderMsg.Append("承保公司分公司不能为空！<br/>");
            }
            if (string.IsNullOrEmpty(insuranceOrder.IMEI))
            {
                validateInsuranceOrderMsg.Append("设备识别码不能为空！<br/>");
            }
            if (string.IsNullOrEmpty(insuranceOrder.CertificateNO))
            {
                validateInsuranceOrderMsg.Append("证件号不能为空！<br/>");
            }
            if (!insuranceOrder.ProductBrandId.HasValue || insuranceOrder.ProductBrandId.Value<1)
            {
                validateInsuranceOrderMsg.Append("请选择本地设备品牌信息！<br/>");
            }
            if (!insuranceOrder.ProductModelId.HasValue ||  insuranceOrder.ProductModelId.Value < 1)
            {
                validateInsuranceOrderMsg.Append("请选择本地设备型号信息！<br/>");
            }
            if (!insuranceOrder.ServiceStartTime.HasValue)
            {
                validateIWRMsg += "保险起期不能为空！<br/>";
            }
            if (!insuranceOrder.ServiceEndTime.HasValue)
            {
                validateIWRMsg += "保险止期不能为空！<br/>";
            }
            if (!insuranceOrder.DeviceType.HasValue)
            {
                validateInsuranceOrderMsg.Append("被保险设备类型不能为空！<br/>");
            }
            if (string.IsNullOrEmpty(insuranceOrder.SaleVendorName))
            {
                validateInsuranceOrderMsg.Append("销售商户名称不能为空！<br/>");
            }
            if (string.IsNullOrEmpty(insuranceOrder.ThirdOrderNO))
            {
                validateInsuranceOrderMsg.Append("第三方保单号不能为空！<br/>");
            }
            if (string.IsNullOrEmpty(insuranceOrder.UserName))
            {
                validateInsuranceOrderMsg.Append("被保险人名字不能为空！<br/>");
            }
            if (string.IsNullOrEmpty(insuranceOrder.UserPhone))
            {
                validateInsuranceOrderMsg.Append("被保险人电话不能为空！<br/>");
            }
            return validateInsuranceOrderMsg.ToString();
        }
        #endregion

        #region 验证报案单数据 + string ValidateInsuranceWarrantyRecordFormData(InsuranceWarrantyRecord iwrEntity)
        /// <summary>
        /// 验证报案单数据
        /// </summary>
        /// <returns></returns>
        internal string ValidateInsuranceWarrantyRecordFormData(InsuranceWarrantyRecord iwrEntity)
        {

            StringBuilder validateIWRMsg = new StringBuilder();
            if (string.IsNullOrEmpty(iwrEntity.Reporter))
            {
                validateIWRMsg.Append("报案人不能为空<br/>");
            }
            if (string.IsNullOrEmpty(iwrEntity.ReporterPhone))
            {
                validateIWRMsg.Append("报案人电话不能为空！<br/>");
            }
            if (iwrEntity.ExpectAccidentDate <= DateTime.MinValue)
            {
                validateIWRMsg.Append("出险日期不能为空！<br/>");
            }
            if (string.IsNullOrEmpty(iwrEntity.AccidentAddress))
            {
                validateIWRMsg.Append("出险地点不能为空！<br/>");
            }
            if (!iwrEntity.ServiceProviderBranchId.HasValue || iwrEntity.ServiceProviderBranchId.Value<1)
            {
                validateIWRMsg.Append("请选择服务商！<br/>");
            }
            return validateIWRMsg.ToString();
        }
        //if ((model.Status == (byte)InsuranceWarrantyStatus.Close))//已处理需要信息完整

        #region 写操作日志 + void WriteOperateLog(InsuranceWarrantyRecord iwrEntity, InsuranceWarrantyRecord model)
        internal void WriteOperateLog(InsuranceWarrantyRecord iwrEntity, InsuranceWarrantyRecord model)
        {
            var opreateLogs = new OpreateLogs
            {
                CreatedTime = DateTime.Now,
                LogTableName = "InsuranceWarrantyRecord",
                LogSubject = "状态与备注",
                LogTablePKID = iwrEntity.ID,
                OpreateUserAccount = CurrentUser.UserAccount,
                OpreateUserName = CurrentUser.UserDisPlayName
            };
            ServiceFactory.OpreateLogsServiceInstance.AddOpreateLogs(opreateLogs, new
            {
                iwrEntity.RepairRemark,
                iwrEntity.Status,
                LastModifyTime = DateTime.Now,
                LastModifyBy = CurrentUser.UserAccount
            }, model);
        }
        #endregion

        #region 写收集信息操作日志 + void WriteOperateLog(InsuranceWarrantyRecord iwrEntity, InsuranceWarrantyRecord model)
        /// <summary>
        /// 写收集信息操作日志
        /// </summary>
        /// <param name="id">报案表主键ID</param>
        /// <param name="entity"></param>
        /// <param name="insuranceWarrantyRecordItem"></param>
        internal void WriteItemOperateLog(long id, InsuranceWarrantyRecordItem entity, InsuranceWarrantyRecordItem insuranceWarrantyRecordItem)
        {

            var opreateLogs = new OpreateLogs
            {
                CreatedTime = DateTime.Now,
                LogTableName = "InsuranceWarrantyRecord",
                LogSubject = "案件处理信息-修改",
                LogTablePKID = id,
                OpreateUserAccount = CurrentUser.UserAccount,
                OpreateUserName = CurrentUser.UserDisPlayName
            };
            ServiceFactory.OpreateLogsServiceInstance.AddOpreateLogs(opreateLogs, new
            {
                insuranceWarrantyRecordItem.LostName,
                insuranceWarrantyRecordItem.LostCount,
                insuranceWarrantyRecordItem.LostPriceForUser,
                insuranceWarrantyRecordItem.LostNuclearPrice,
            }, entity);
        }
        #endregion

        #region 操作流程日志 + void WriteProcessLog(InsuranceWarrantyRecordStatus oldStatusInfo, InsuranceWarrantyRecordStatus newStatusInfo,int? StatusReasonId)
        /// <summary>
        /// 操作流程日志
        /// </summary>
        /// <param name="oldStatusInfo">旧状态信息</param>
        /// <param name="newStatusInfo">新状态信息</param>
        /// <param name="statusReasonId">状态备注ID</param>
        /// <param name="Id">报案工单ID</param>
        public void WriteProcessLog(InsuranceWarrantyRecordStatus oldStatusInfo, InsuranceWarrantyRecordStatus newStatusInfo, int? statusReasonId, long Id)
        {
            if (oldStatusInfo == null || newStatusInfo == null)
                return;
            ProcessLogs log = new ProcessLogs()
            {
                InsuranceWarrantyRecordId = Id,
                BeforeProcessStatusId = oldStatusInfo.ID,
                BeforeProcessStatusCode = oldStatusInfo.StatusCode,
                BeforeProcessStatusName = oldStatusInfo.StatusName,
                ProcessStatusId = newStatusInfo.ID,
                ProcessStatusCode = newStatusInfo.StatusCode,
                ProcessStatusName = newStatusInfo.StatusName,
                CreateTime = DateTime.Now,
                CreateUserId = (int)CurrentUser.ID,
                CreateByName = CurrentUser.UserDisPlayName,
                CreateByAccount = CurrentUser.UserAccount
            };
            if (statusReasonId.HasValue && statusReasonId.Value > 0)
            {
                StatusReason reason = ServiceFactory.StatusReasonServiceInstance.LoadEntities(t => t.ID == statusReasonId.Value).FirstOrDefault();
                if (reason != null)
                {
                    log.ReasonDescribe = reason.ReasonDescribe;
                    log.StatusReasonId = reason.ID;
                }
            }
            log = ServiceFactory.ProcessLogsServiceInstance.AddEntities(log);
            if (log.ID < 1)
            {
                LogHelper.WriteLog(string.Format("修改报案状态保持数据库失败：状态由{0}修改为{1}。", oldStatusInfo.StatusCode, newStatusInfo.StatusCode), LogType.remark);
            }
        }
        #endregion

        #endregion

        #region 保存回访信息 + ActionResult SaveReturnVisit(InsuranceWarrantyRecord model)
        /// <summary>
        /// 保存回访信息
        /// </summary>
        /// <param name="model"></param>
        /// <returns></returns>
        public ActionResult SaveReturnVisit(InsuranceWarrantyRecord model)
        {
            var responseResult = new ResponseResult
            {
                OpreateType = OpreateType.Update
            };
            var entity = ServiceFactory.InsuranceWarrantyRecordServiceInstance.LoadByID(model.ID);
            if (entity != null)
            {
                model.Status = (byte)InsuranceWarrantyStatus.RetrurnVisited;
                model.LastModifyBy = CurrentUser.UserAccount;
                model.LastModifyTime = DateTime.Now;
                #region 先记录日志
                var opreateLogs = new OpreateLogs
                {
                    CreatedTime = DateTime.Now,
                    LogTableName = "InsuranceWarrantyRecord",
                    LogSubject = "回访信息",
                    LogTablePKID = entity.ID,
                    OpreateUserAccount = CurrentUser.UserAccount,
                    OpreateUserName = CurrentUser.UserDisPlayName
                };
                var logEntity = new
                {
                    entity.ReturnVisitTime,
                    entity.ReturnVisitResult,
                    entity.WarrantyServiceScore,
                    entity.LastModifyBy,
                    entity.LastModifyTime,
                    entity.Status,
                };
                var addLogResult = ServiceFactory.OpreateLogsServiceInstance.AddOpreateLogs(opreateLogs, logEntity, model);
                #endregion
                entity.ReturnVisitTime = DateTime.Now;
                entity.ReturnVisitResult = model.ReturnVisitResult;
                entity.WarrantyServiceScore = model.WarrantyServiceScore;
                entity.LastModifyBy = model.LastModifyBy;
                entity.LastModifyTime = model.LastModifyTime;
                entity.Status = model.Status;
                responseResult.Success = ServiceFactory.InsuranceWarrantyRecordServiceInstance.UpdateEntities(entity);
            }
            TempData["ResponseResult"] = responseResult;
            return RedirectToAction("Processing", new { id = model.ID });
        }
        #endregion

        #endregion

        #region 导出已处理任务
        /// <summary>
        /// 导出已处理任务
        /// </summary>
        /// <returns></returns>
        public JsonResult ExportInsuranceWarrantyRecord(string content, string zipFileName, bool isNeedLoadFile, InsuranceWarrantyRecordItemModel model1)
        {
            InsuranceWarrantyRecordModel model = JsonConvert.DeserializeObject<InsuranceWarrantyRecordModel>(content);
            model.iDisplayLength = int.MaxValue;
            var total = 0;
            var OrderNum = 0;
            //1、获取数据列表
            var list =
                (from b in
                     ServiceFactory.InsuranceWarrantyRecordServiceInstance.GetPagingList(model, out total)
                 join a in
                     ServiceFactory.InsuranceWarrantyRecordItemServiceInstance.LoadEntities(n => true).AsEnumerable()
                     on b.ID equals a.InsuranceWarrantyRecordId into temp
                 from c in temp.DefaultIfEmpty()
                 join d in ServiceFactory.InsuranceOrderServiceInstance.LoadEntities(n => true) on b.InsuranceOrderId equals d.ID
                 into temp1
                 from f in temp1.DefaultIfEmpty()
                 join q in ServiceFactory.SystemUserServiceInstance.LoadEntities(n => true) on b.SystemServiceUserId equals q.ID into temp2
                 from m in temp2.DefaultIfEmpty()
                 select new ExportInsuranceWarrantyRecordModel
                 {
                     WarrantyRecordNo = b.WarrantyRecordNo,//保案单号
                     Reporter = b.Reporter,//报案人
                     ReporterPhone = b.ReporterPhone,//报案人电话
                     AccidentAddressDesc = b.AccidentAddress,//出险地址
                     Remark = b.Remark,//备注信息                      
                     Status = b.Status,////工单状态
                     CreateTimeTemp = b.CreateTime,//创建日期
                     UserDisPlayName = m != null ? m.UserDisPlayName : string.Empty,//跟进人
                     LastModifyTime = b.LastModifyTime,//关单时间
                     InsuranceCompany = f.InsuranceCompany,//第三方承保公司
                     InsuranceCompanyBranch = f.InsuranceCompanyBranch,//承保公司
                     ProductName = f.ProductName,//保险产品名称
                     ProductBrandName = f.ProductBrandName,//被保险设备品牌
                     ProductModelName = f.ProductModelName,//被保险设备型号
                     SaleVendorName = f.SaleVendorName,//销售商户名称
                     InsuranceCategoryName = f.InsuranceCategoryName,//保险产品类别
                     ThirdOrderNO = f.ThirdOrderNO,//第三方保单号
                     UserName = f.UserName,//被保险人名称
                     UserPhone = f.UserPhone,//被保险人电话
                     CertificateNO = f.CertificateNO,//证件号
                     IMEI = f.IMEI,//被保险设备识别码
                     LostName = c != null ? c.LostName : string.Empty,//损失名称
                     LostPriceForUser = c != null ? c.LostPriceForUser : decimal.Zero,//经销商价格
                     LostNuclearPrice = c != null ? c.LostNuclearPrice : decimal.Zero,//保险结算价
                 }).ToList();
            var total2 = 0;
            var list2 = ServiceFactory.InsuranceWarrantyRecordServiceInstance.GetPagingList(model, out total2)
                .Select(o => new
                {
                    o.Reporter,
                    o.CreateTime,
                    o.ReporterPhone,
                    o.WarrantyRecordNo
                }).ToList();
            if (isNeedLoadFile)
            {
                //2、获取需要压缩的文件夹列表total2
                string[] fileDir = new string[list2.Count()];
                for (int i = 0, j = fileDir.Length; i < j; i++)
                {
                    var itemList = list2[i];
                    DateTime createTime = Convert.ToDateTime(itemList.CreateTime);
                    //1銆侊紙淇濆瓨璺緞蹇呴』涓?SocketChatController/CollectData涓嬬殑涓€鑷达級  骞?鏈?鏃?濮撳悕_鎵嬫満_鎶ユ鍗曞彿/绱犳潗绫诲瀷
                    string folderName = string.Format("/UploadFile/File/workOrder/{0}/{1}/{2}/{3}_{4}_{5}", createTime.Year, createTime.Month, createTime.Day, itemList.Reporter, itemList.ReporterPhone, itemList.WarrantyRecordNo);
                    fileDir[i] = Server.MapPath(folderName);
                }
                //3、异步压缩文件
                FileHelper.ZipFile(fileDir, Server.MapPath("/UploadFile/File/zipOrder"), zipFileName + ".zip");
            }

            //4、把数据导出excel
            var dt = ListToDatatableHelper.ToDataTable(list);
            dt.TableName = "List";
            List<DataTable> dataSoure = new List<DataTable> { dt };
            Dictionary<string, object> dic = new Dictionary<string, object>();
            string execlPath = Server.MapPath("\\").Trim('\\') + "\\ExportTemplate\\InsuranceWarrantyRecordList.xlsx";
            string fileName = "已处理任务清单_" + DateTime.Now.ToString("yyyyMMddhhmmss");
            ExcelHelper.ExportToExcel(execlPath, dic, dataSoure, fileName);
            return Json(new object { });
        }

        #region 导出已处理任务的压缩文件
        [HttpPost]
        public JsonResult DownloadFiles(string content)
        {
            // 判断文件是否生成 
            bool result = FileHelper.ReadFileStream(Server.MapPath(content));
            return Json(new { sucess = result, message = result ? content : "文件尚未生成，请稍后再试！" });
        }
        #endregion
        #endregion

        #region 补充报案信息
        public ActionResult Edit(int id)
        {
            var insuranceWarrantyRecord =
                ServiceFactory.InsuranceWarrantyRecordServiceInstance.LoadByID(id) ?? new InsuranceWarrantyRecord();
            if (insuranceWarrantyRecord.InsuranceOrder == null)
                insuranceWarrantyRecord.InsuranceOrder =
                    ServiceFactory.InsuranceOrderServiceInstance.LoadByID(insuranceWarrantyRecord.InsuranceOrderId);
            if (string.IsNullOrEmpty(insuranceWarrantyRecord.Reporter))
                insuranceWarrantyRecord.Reporter = insuranceWarrantyRecord.InsuranceOrder.UserName;

            if (string.IsNullOrEmpty(insuranceWarrantyRecord.ReporterPhone))
                insuranceWarrantyRecord.ReporterPhone = insuranceWarrantyRecord.InsuranceOrder.UserPhone;
            return View(insuranceWarrantyRecord);
        }
        #endregion

        #region 收集资料
        public ActionResult IWRDataCollect(int insuranceWarrantyRecordId)
        {
            var insuranceWarrantyRecord = ServiceFactory.InsuranceWarrantyRecordServiceInstance.LoadByID(insuranceWarrantyRecordId);
            byte parentStatus = ServiceFactory.InsuranceWarrantyRecordStatusServiceInstance.GetParentStatusCode(insuranceWarrantyRecord.Status);
            ViewBag.ParentStatus = parentStatus;
            return View(insuranceWarrantyRecord);
        }

        /// <summary>
        /// 保存收集资料（图片）
        /// </summary>
        /// <param name="model"></param>
        /// <returns></returns>
        [HttpPost]
        public ActionResult SaveIWRImages(InsuranceWarrantyRecord model)
        {
            var responseResult = new ResponseResult
            {
                OpreateType = OpreateType.Update
            };
            if (model.ID < 1)
            {
                responseResult.Message = "参数错误";
            }
            else if (string.IsNullOrEmpty(Request["InsuranceWarrantyRecordImages"]))
            {
                responseResult.Message = "请选择图片类型";
            }
            else
            {
                var entity = new InsuranceWarrantyRecordImages { InsuranceWarrantyRecordId = model.ID };
                var iwrImages = Request.Files;
                EnumHelper enumHelper = EnumHelper.Instance;
                string imageType = Request["InsuranceWarrantyRecordImages"];
                //1、（保存路径必须与/SocketChatController/CollectData下的一致）
                string folderName = string.Format("/UploadFile/File/workOrder/{0}/{1}/{2}/{3}_{4}_{5}/{6}/", model.CreateTime.Year, model.CreateTime.Month, model.CreateTime.Day, model.Reporter, model.ReporterPhone.Trim(), model.WarrantyRecordNo, enumHelper.GetDescription(typeof(WarrantyRecordImageEnums), imageType));
                string fullPath = Server.MapPath(folderName);
                if (iwrImages != null && iwrImages.Count > 0)
                {
                    for (int i = 0; i < iwrImages.Count; i++)
                    {
                        var iwrImage = iwrImages[i];
                        if (iwrImage == null)
                        {
                            responseResult.Message = "选择的图片格式有误或者没有选择上传的图片！";
                            continue;
                        }
                        //var filePath = FileHelper.UploadFile(iwrImage, Server, folderName);
                        string fileName = System.Guid.NewGuid().ToString() + ".png";
                        bool result = FileHelper.GetPicThumbnail(iwrImage, 0, fullPath, fileName);
                        if (!result)
                        {
                            responseResult.Message = "图片保存错误！";
                            continue;
                        }
                        entity.FileName = fileName;
                        entity.FilePath = folderName + fileName;
                        entity.FileSize = "";
                        entity.IsAvailable = true;
                        entity.CreateBy = CurrentUser.UserAccount;
                        entity.CreateTime = DateTime.Now;
                        entity.ImageType = Convert.ToByte(imageType); //资料类型
                        responseResult.Success = ServiceFactory.InsuranceWarrantyRecordImagesServiceInstance.AddEntities(entity).ID > 0;
                    }
                }
            }
            TempData["ResponseResult"] = responseResult;
            return RedirectToAction("IWRDataCollect", new
            {
                insuranceWarrantyRecordId = model.ID
            });
        }

        /// <summary>
        /// 删除图片
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        [HttpPost]
        public JsonResult DeleteIWRImage(int id)
        {
            var iwrImage = ServiceFactory.InsuranceWarrantyRecordImagesServiceInstance.LoadByID(id);
            var result = false;
            if (iwrImage != null)
                result = ServiceFactory.InsuranceWarrantyRecordImagesServiceInstance.DeleteEntities(iwrImage);
            return Json(new { sucess = result, message = result ? "删除成功！" : "删除失败！" });
        }

        #endregion

        #region 取件信息
        /// <summary>
        /// 取件信息
        /// </summary>
        /// <returns></returns>
        public ActionResult IWRPickUpInfo(int id)
        {
            var order = ServiceFactory.InsuranceWarrantyRecordServiceInstance.LoadByID(id);
            if (string.IsNullOrWhiteSpace(order.SendUserName))
            {
                order.SendUserName = order.InsuranceOrder.UserName;
            }
            if (string.IsNullOrWhiteSpace(order.SendUserPhone))
            {
                order.SendUserPhone = order.InsuranceOrder.UserPhone;
            }
            if (string.IsNullOrWhiteSpace(order.SendUserAddress))
            {
                order.SendUserAddress = order.D_Province.ProvinceName + order.D_City.CityName + order.AccidentAddress;
            }
            byte parentStatus = ServiceFactory.InsuranceWarrantyRecordStatusServiceInstance.GetParentStatusCode(order.Status);
            ViewBag.ParentStatus = parentStatus;
            return View(order);
        }

        /// <summary>
        /// 保存取件信息
        /// </summary>
        /// <param name="model"></param>
        /// <returns></returns>
        public ActionResult SaveIWRPickUp(InsuranceWarrantyRecord model)
        {
            var responseResult = new ResponseResult
            {
                OpreateType = OpreateType.Save
            };
            using (TransactionScope sc = new TransactionScope())
            {
                try
                {
                    var entity = ServiceFactory.InsuranceWarrantyRecordServiceInstance.LoadByID(model.ID);
                    if (entity != null)
                    {
                        #region 先记录日志
                        var opreateLogs = new OpreateLogs
                        {
                            CreatedTime = DateTime.Now,
                            LogTableName = "InsuranceWarrantyRecord",
                            LogSubject = "取件信息",
                            LogTablePKID = entity.ID,
                            OpreateUserAccount = CurrentUser.UserAccount,
                            OpreateUserName = CurrentUser.UserDisPlayName
                        };
                        var addLogResult = ServiceFactory.OpreateLogsServiceInstance.AddOpreateLogs(opreateLogs, new
                        {
                            entity.SendExpress,
                            entity.SendExpressNo,
                            entity.SendUserName,
                            entity.SendUserPhone,
                            entity.SendUserAddress,
                            entity.SendSignTime,
                            entity.SendSignUserName,
                            entity.SendExpressPickUpTime,
                        }, model);
                        #endregion
                        entity.SendExpress = model.SendExpress;
                        entity.SendExpressNo = model.SendExpressNo;
                        entity.SendUserName = model.SendUserName;
                        entity.SendUserPhone = model.SendUserPhone;
                        entity.SendUserAddress = model.SendUserAddress;
                        entity.SendSignTime = DateTime.Now;
                        entity.SendSignUserName = model.SendSignUserName;
                        entity.SendExpressPickUpTime = model.SendExpressPickUpTime;
                        responseResult.Success = ServiceFactory.InsuranceWarrantyRecordServiceInstance.UpdateEntities(entity);
                    }
                    sc.Complete();

                }
                catch (Exception ex)
                {
                    responseResult.Message = ex.Message;
                    sc.Dispose();
                }
            }
            TempData["ResponseResult"] = responseResult;
            return RedirectToAction("IWRPickUpInfo", new { id = model.ID });
        }
        #endregion

        #region 寄件信息
        /// <summary>
        /// 寄（寄回）修件信息
        /// </summary>
        /// <returns></returns>
        public ActionResult SendBackInfo(int id)
        {
            var order = ServiceFactory.InsuranceWarrantyRecordServiceInstance.LoadByID(id);
            //没有保存值则取默认值
            if (string.IsNullOrWhiteSpace(order.SendBackToUserName))
            {
                order.SendBackToUserName = order.InsuranceOrder.UserName;
            }
            if (string.IsNullOrWhiteSpace(order.SendBackToUserPhone))
            {
                order.SendBackToUserPhone = order.InsuranceOrder.UserPhone;
            }
            if (string.IsNullOrWhiteSpace(order.SendBackToAddress))
            {
                order.SendBackToAddress = order.D_Province.ProvinceName + order.D_City.CityName + order.AccidentAddress;
            }
            if (!order.SendBackToProvinceId.HasValue)
            {
                order.SendBackToProvinceId = order.ProvinceId;
            }
            if (!order.SendBackToCityId.HasValue)
            {
                order.SendBackToCityId = order.CityId;
            }
            byte parentStatus = ServiceFactory.InsuranceWarrantyRecordStatusServiceInstance.GetParentStatusCode(order.Status);
            ViewBag.ParentStatus = parentStatus;
            return View(order);
        }
        /// <summary>
        /// 保存寄件信息
        /// </summary>
        /// <param name="model"></param>
        /// <returns></returns>
        public ActionResult SaveSendBackInfo(InsuranceWarrantyRecord model)
        {
            var responseResult = new ResponseResult
            {
                OpreateType = OpreateType.Save
            };
            using (TransactionScope sc = new TransactionScope())
            {
                try
                {
                    var entity = ServiceFactory.InsuranceWarrantyRecordServiceInstance.LoadByID(model.ID);
                    if (entity != null)
                    {
                        #region 先记录日志
                        var opreateLogs = new OpreateLogs
                        {
                            CreatedTime = DateTime.Now,
                            LogTableName = "InsuranceWarrantyRecord",
                            LogSubject = "寄件信息",
                            LogTablePKID = entity.ID,
                            OpreateUserAccount = CurrentUser.UserAccount,
                            OpreateUserName = CurrentUser.UserDisPlayName
                        };
                        var addLogResult = ServiceFactory.OpreateLogsServiceInstance.AddOpreateLogs(opreateLogs, new
                        {
                            entity.SendBackExpress,
                            entity.SendBackExpressNo,
                            entity.SendBackToUserName,
                            entity.SendBackToUserPhone,
                            entity.SendBackToProvinceId,
                            entity.SendBackToCityId,
                            entity.SendBackToAddress,
                            entity.SendBackUserName,
                            entity.SendBackUserPhone,
                            entity.SendBackTime,
                            entity.SendSignUserName
                        }, model);
                        #endregion
                        entity.SendBackExpress = model.SendBackExpress;
                        entity.SendBackExpressNo = model.SendBackExpressNo;
                        entity.SendBackToUserName = model.SendBackToUserName;
                        entity.SendBackToUserPhone = model.SendBackToUserPhone;
                        entity.SendBackToProvinceId = model.SendBackToProvinceId;
                        entity.SendBackToCityId = model.SendBackToCityId;
                        entity.SendBackToAddress = model.SendBackToAddress;
                        entity.SendBackUserName = model.SendBackUserName;
                        entity.SendBackUserPhone = model.SendBackUserPhone;
                        entity.SendBackTime = DateTime.Now;
                        entity.SendSignUserName = CurrentUser.UserDisPlayName;
                        responseResult.Success = ServiceFactory.InsuranceWarrantyRecordServiceInstance.UpdateEntities(entity);
                    }
                    sc.Complete();
                }
                catch (Exception ex)
                {
                    responseResult.Message = ex.Message;
                    sc.Dispose();
                }
            }
            TempData["ResponseResult"] = responseResult;
            return RedirectToAction("SendBackInfo", new { id = model.ID });
        }
        #endregion

        #region 无保单案件，根据第三方系统唯一编号，如果没有保单信息，则创建新的保单，否则更新之
        /// <summary>
        /// 创建无保单案件
        /// </summary>
        /// <returns></returns>
        public ActionResult CreateNoInsuranceOrderIWR()
        {
            return View();
        }
        /// <summary>
        /// 保存无保单案件
        /// </summary>
        /// <param name="iwRecord"></param>
        /// <returns></returns>
        public ActionResult SaveNoInsuranceOrderIWR(InsuranceWarrantyRecord iwRecord)
        {
            var responseResult = new ResponseResult();
            var insuranceOrderModel = iwRecord.InsuranceOrder;
            var insuranceOrder = ServiceFactory.InsuranceOrderServiceInstance.LoadByThirdUniqueNumber(insuranceOrderModel.ThirdUniqueNumber);
            var result = false;
            long insuranceId = 0;
            if (insuranceOrder == null)
            {
                responseResult.OpreateType = OpreateType.Add;

                insuranceOrderModel.CreateBy = CurrentUser.UserAccount;
                insuranceOrderModel.OrderStatus = (byte)InsuranceOrderStatus.HadEffective;//
                insuranceOrderModel.OrderNO = CommonMethod.GetNewOrderNo();//工单号
                insuranceOrderModel.LastModifyBy = CurrentUser.UserAccount;
                insuranceOrderModel.LastModifyTime = DateTime.Now;
                insuranceOrderModel.Price = 0;//默认为0
                insuranceOrderModel.BuyType = (byte)InsuranceBuyType.NonActivationCodeBuy;//非激活购买
                insuranceOrderModel.Effective = true;//生效
                insuranceOrderModel.WaitDays = 0;
                insuranceOrderModel.CertificateNO = insuranceOrderModel.CertificateNO.Trim() ?? "";
                insuranceOrderModel.CreateOrderTime = insuranceOrderModel.CreateOrderTime > DateTime.MinValue
                    ? insuranceOrderModel.CreateOrderTime
                    : DateTime.Now;
                insuranceOrderModel.ProductBrandName = insuranceOrderModel.ProductBrandName ?? "";
                insuranceOrderModel.ProductModelName = insuranceOrderModel.ProductModelName ?? "";
                if (insuranceOrderModel.ServiceStartTime != null)
                {
                    insuranceOrderModel.EffectiveDate = insuranceOrderModel.ServiceStartTime.Value.AddDays(insuranceOrderModel.WaitDays);
                    if (insuranceOrderModel.ServiceEndTime != null)
                        insuranceOrderModel.PolicyPeriod = (int)(insuranceOrderModel.ServiceEndTime.Value - insuranceOrderModel.ServiceStartTime.Value).TotalDays + 1;
                }

                insuranceOrderModel.PolicyPeriodUnit = (byte)InsuranceOrderPeriodUnit.Day;
                insuranceOrderModel.OrderFromType = (byte)InsuranceOrderFromType.FromNoInsuranceIWR;
                insuranceId = ServiceFactory.InsuranceOrderServiceInstance.AddEntities(insuranceOrderModel).ID;
                responseResult.Success = insuranceId > 0;
            }
            else
            {
                responseResult.OpreateType = OpreateType.Update;

                insuranceId = insuranceOrder.ID;

                insuranceOrder.LastModifyBy = CurrentUser.UserAccount;
                insuranceOrder.LastModifyTime = DateTime.Now;
                insuranceOrder.InsuranceCategoryName = insuranceOrderModel.InsuranceCategoryName;
                insuranceOrder.ProductName = insuranceOrderModel.ProductName;
                insuranceOrder.ProductTypeId = insuranceOrderModel.ProductTypeId;
                insuranceOrder.CertificateType = insuranceOrderModel.CertificateType;
                insuranceOrder.InsuranceCompanyBranch = insuranceOrderModel.InsuranceCompanyBranch;
                insuranceOrder.DeviceType = insuranceOrderModel.DeviceType;
                insuranceOrder.ProductBrandId = insuranceOrderModel.ProductBrandId;
                insuranceOrder.SaleVendorId = insuranceOrderModel.SaleVendorId;
                insuranceOrder.SaleVendorName = insuranceOrderModel.SaleVendorName;
                insuranceOrder.ProductModelId = insuranceOrderModel.ProductModelId;
                insuranceOrder.IMEI = insuranceOrderModel.IMEI;
                insuranceOrder.UserName = insuranceOrderModel.UserName;
                insuranceOrder.CreateOrderTime = insuranceOrderModel.CreateOrderTime > DateTime.MinValue
                    ? insuranceOrderModel.CreateOrderTime
                    : DateTime.Now;
                insuranceOrder.UserPhone = insuranceOrderModel.UserPhone.Trim();
                if (insuranceOrderModel.ServiceStartTime != null)
                {
                    insuranceOrder.EffectiveDate = insuranceOrderModel.ServiceStartTime.Value.AddDays(insuranceOrderModel.WaitDays);
                    if (insuranceOrderModel.ServiceEndTime != null)
                    {
                        insuranceOrder.PolicyPeriod = (int)(insuranceOrderModel.ServiceEndTime.Value - insuranceOrderModel.ServiceStartTime.Value).TotalDays + 1;
                    }
                }
                insuranceOrder.CertificateNO = insuranceOrderModel.CertificateNO.Trim() ?? "";
                insuranceOrder.ProductBrandName = insuranceOrderModel.ProductBrandName ?? "";
                insuranceOrder.ProductModelName = insuranceOrderModel.ProductModelName ?? "";
                insuranceOrder.InsuredAmount = insuranceOrderModel.InsuredAmount;
                responseResult.Success = ServiceFactory.InsuranceOrderServiceInstance.UpdateEntities(insuranceOrder);
            }
            if (responseResult.Success)//先创建保单，再新建案件
            {
                responseResult.OpreateType = OpreateType.Add;
                var iwrEntiry = ServiceFactory.InsuranceWarrantyRecordServiceInstance.LoadByInsuranceOrderId(insuranceId).FirstOrDefault(c => c.Status != (byte)InsuranceWarrantyStatus.Canceled && c.Status != (byte)InsuranceWarrantyStatus.Refuse);//已取消报案和拒赔的可以再次报案
                if (iwrEntiry == null)
                {
                    iwrEntiry = new InsuranceWarrantyRecord
                    {
                        InsuranceOrderId = insuranceId,
                        Reporter = insuranceOrderModel.UserName,
                        ReporterPhone = insuranceOrderModel.UserPhone,
                        ExpectAccidentDate = iwRecord.ExpectAccidentDate > DateTime.MinValue ? iwRecord.ExpectAccidentDate : DateTime.Now,
                        CityId = iwRecord.CityId,
                        ProvinceId = iwRecord.ProvinceId,
                        AccidentAddress = iwRecord.AccidentAddress,
                        AccidentProsess = iwRecord.AccidentProsess,
                        Remark = iwRecord.Remark,
                        WarrantyRecordNo = CommonMethod.GetTimeStamp(),
                        CreateTime = DateTime.Now,
                        CreateBy = insuranceOrderModel.LastModifyBy = CurrentUser.UserAccount,
                        LastModifyBy = CurrentUser.UserAccount,
                        LastModifyTime = DateTime.Now,
                        Status = (byte)InsuranceWarrantyStatus.Created,
                        SystemServiceUserId = CurrentUser.ID
                    };
                    var id = ServiceFactory.InsuranceWarrantyRecordServiceInstance.AddEntities(iwrEntiry).ID;
                    responseResult.Success = id > 0;
                }
                else
                {
                    responseResult.OpreateType = OpreateType.Update;
                    iwrEntiry.Reporter = insuranceOrderModel.UserName;
                    iwrEntiry.ReporterPhone = insuranceOrderModel.UserPhone;
                    iwrEntiry.ExpectAccidentDate = iwRecord.ExpectAccidentDate > DateTime.MinValue ? iwRecord.ExpectAccidentDate : DateTime.Now;
                    iwrEntiry.CityId = iwRecord.CityId;
                    iwrEntiry.ProvinceId = iwRecord.ProvinceId;
                    iwrEntiry.AccidentAddress = iwRecord.AccidentAddress;
                    iwrEntiry.AccidentProsess = iwRecord.AccidentProsess;
                    iwrEntiry.Remark = iwRecord.Remark;
                    iwrEntiry.LastModifyBy = CurrentUser.UserAccount;
                    iwrEntiry.LastModifyTime = DateTime.Now;
                    responseResult.Success = ServiceFactory.InsuranceWarrantyRecordServiceInstance.UpdateEntities(iwrEntiry);
                }
            }
            TempData["ResponseResult"] = responseResult;
            return RedirectToAction("ToBeCreated");
        }
        #endregion

        #region 导出已处理案件 + ActionResult ExportInsuranceWarrantyRecordList(InsuranceWarrantyRecordModel model)
        [HttpPost]
        public ActionResult ExportInsuranceWarrantyRecordList(InsuranceWarrantyRecordModel model, InsuranceWarrantyRecordItemModel model1)
        {
            model.iDisplayLength = int.MaxValue;
            var total = 0;
            var list = ServiceFactory.InsuranceWarrantyRecordServiceInstance.GetPagingList(model, out total).Include(o => o.SystemUser).Include(o => o.InsuranceOrder).AsNoTracking().ToList().Select((o, i) => new
            {
                o.ID,
                o.InsuranceOrderId,
                o.WarrantyRecordNo,
                o.Reporter,
                o.ReporterPhone,
                o.ContactName,
                o.ContactPhone,
                o.ExpectAccidentDate,
                o.ProvinceId,
                o.CityId,
                AccidentAddress = (o.ProvinceId.HasValue ? o.D_Province.ProvinceName : "") + (o.CityId.HasValue ? o.D_City.CityName : "") + o.AccidentAddress,
                o.AccidentProsess,
                o.Remark,
                o.SystemServiceUserId,
                o.SendExpress,
                o.SendExpressNo,
                o.SendUserName,
                o.SendUserPhone,
                o.SendUserAddress,
                o.SendSignTime,
                o.SendSignUserName,
                o.RepairRemark,
                o.RepairFinishTime,
                o.SendBackExpress,
                o.SendBackExpressNo,
                o.SendBackToUserName,
                o.SendBackToUserPhone,
                o.SendBackToProvinceId,
                o.SendBackToCityId,
                o.SendBackToAddress,
                o.SendBackUserName,
                o.SendBackUserPhone,
                SendBackTime = o.SendBackTime.HasValue ? o.SendBackTime.Value.ToString("yyyy-MM-dd HH:mm:ss") : "",
                o.Status,
                StatusDesc = ServiceFactory.InsuranceWarrantyRecordStatusServiceInstance.GetStatusName(o.Status),
                CreateTime = o.CreateTime.ToString("yyyy-MM-dd HH:mm:ss"),
                o.CreateBy,
                LastModifyTime = o.LastModifyTime.ToString("yyyy-MM-dd HH:mm:ss"),
                o.LastModifyBy,
                ServiceName = o.SystemUser != null ? o.SystemUser.UserDisPlayName : string.Empty,
                SendExpressPickUpTime = o.SendExpressPickUpTime.HasValue ? o.SendExpressPickUpTime.Value.ToString("yyyy-MM-dd HH:mm:ss") : "",
                SingleTime = o.Status == 20 ? o.LastModifyTime : DateTime.MinValue,
                o.InsuranceOrder.InsuranceCompany,
                o.InsuranceOrder.InsuranceCompanyBranch,
                o.InsuranceOrder.ProductName,
                o.InsuranceOrder.ProductBrandName,
                o.InsuranceOrder.ProductModelName,
                o.InsuranceOrder.ProductTypeName,
                o.InsuranceOrder.SaleVendorName,
                o.InsuranceOrder.InsuranceCategoryName,
                o.InsuranceOrder.ThirdOrderNO,
                o.InsuranceOrder.UserName,
                o.InsuranceOrder.UserPhone,
                o.InsuranceOrder.CertificateNO,
                o.InsuranceOrder.IMEI,
                OrderNum = ++i,
            });
            var dt = ListToDatatableHelper.ToDataTable(list.ToList());
            dt.TableName = "List";
            List<DataTable> dataSoure = new List<DataTable> { dt };
            Dictionary<string, object> dic = new Dictionary<string, object>();
            string url = "";
            if (model.InsuranceWarrantyRecordTaskType.HasValue)
            {
                url = model.InsuranceWarrantyRecordTaskType.Value == InsuranceWarrantyRecordTaskType.ToBeProcess ? "InsuranceWarrantySuspend.xlsx" : "InsuranceWarrantyRecordList.xlsx";
            }
            string execlPath = Server.MapPath("\\").Trim('\\') + "\\ExportTemplate\\" + url;

            string fileName = model.InsuranceWarrantyRecordTaskType != null && model.InsuranceWarrantyRecordTaskType.Value == InsuranceWarrantyRecordTaskType.ToBeProcess ? "待处理任务清单_" + DateTime.Now.ToString("yyyyMMddhhmmss") : "已处理任务清单_" + DateTime.Now.ToString("yyyyMMddhhmmss");
            ExcelHelper.ExportToExcel(execlPath, dic, dataSoure, fileName);
            return RedirectToAction("InsuranceWarrantyRecord",
                new { InsuranceWarrantyRecordTaskType = (int)InsuranceWarrantyRecordTaskType.Processed });
        }
        #endregion

        #region 报案工单操作流程日志
        public ActionResult ProcessLogsIndex(long InsuranceWarrantyRecordId)
        {
            ViewBag.InsuranceWarrantyRecordId = InsuranceWarrantyRecordId;
            return View();
        }

        [HttpPost]
        public ActionResult ProcessLogsList(ProcessLogsModel model)
        {
            var total = 0;
            var list = ServiceFactory.ProcessLogsServiceInstance.GetPagingList(model, out total).AsNoTracking().ToList().Select(o => new
            {
                o.ID,
                o.BeforeProcessStatusName,
                o.ProcessStatusName,
                o.ReasonDescribe,
                CreateTime = o.CreateTime.ToString("yyyy-MM-dd HH:mm:ss"),
                o.CreateByName,
            });
            return Json(new
            {
                sEcho = model.sEcho,
                iTotalRecords = total,
                iTotalDisplayRecords = total,
                aaData = list
            }, JsonRequestBehavior.AllowGet);
        }
        #endregion

        #endregion
    }
}